package com.apkcore.core.util

import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.apkcore.core.cp.ApkcoreContentProvider


/**
 * @author chanehao
 * @date 2022/12/24
 * @apiNote
 */
object SoundPoolManager {
    private const val TAG = "SoundPoolManager"

    private var lastSound = ""
    private var lastTime = 0L
    private var soundPool: SoundPool =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            //AudioAttributes是一个封装音频各种属性的方法
            val attrBuilder = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                //设置音频流的合适的属性
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                .build()
            SoundPool.Builder()
                //传入最多播放音频数量,
                .setMaxStreams(1)
                //加载一个AudioAttributes
                .setAudioAttributes(attrBuilder)
                .build()
        } else {
            /**
             * 第一个参数：int maxStreams：SoundPool对象的最大并发流数
             * 第二个参数：int streamType：AudioManager中描述的音频流类型
             * 第三个参数：int srcQuality：采样率转换器的质量。 目前没有效果。 使用0作为默认值。
             */
            SoundPool(1, AudioManager.STREAM_MUSIC, 0)
        }

    private var soundMap = HashMap<String, Int>()


    fun initSounds(lifecycleOwner: LifecycleOwner? = null) {
        val files = ApkcoreContentProvider.appContext.resources.assets.list("wav")
        files?.forEach { str ->
            if (str.endsWith(".mp3") || str.endsWith(".wav")) {
                val fileName = str.substring(0, str.lastIndexOf("."))
                soundMap[fileName] =
                    soundPool.load(ApkcoreContentProvider.appContext.assets.openFd("wav/$str"), 1)
            }
        }
        lifecycleOwner?.lifecycle?.addObserver(object :DefaultLifecycleObserver{
            override fun onDestroy(owner: LifecycleOwner) {
                release()
                super.onDestroy(owner)
            }
        })
    }

    // 在须要播放音频的地方把要播放的是哪首和要播放的遍数传进去
    fun playSound(soundName: String, loop: Int = 0) {
        if (System.currentTimeMillis() - lastTime < 2000) {
            return
        }
        Log.d(TAG, "playSound: $soundName")
        lastTime = System.currentTimeMillis()
        lastSound = soundName
        if (soundMap.contains(soundName)) {
            soundPool.play(soundMap[soundName]!!, 1f, 1f, 1, loop, 1.0f)
        }
    }

    fun release() {
        soundPool.release()
    }
}